﻿using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;
using DAL;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GmkCollege.aliPay
{
    public class AlipayConfigHelper
    {
        ////↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

        ////支付宝网关地址
        //// -----开发环境地址-----
        //// -----沙箱地址-----
        //public static string serviceUrl = "https://openapi.alipaydev.com/gateway.do";
        //// -----线上地址-----
        ////public static string serviceUrl = "https://openapi.alipay.com/gateway.do"; 

        ////应用ID,以2088开头由16位纯数字组成的字符串
        //public static string appId = "2021000117662422";
        ////开发者私钥，由开发者自己生成
        //public static string privateKey = @"MIIEowIBAAKCAQEAqAgs3DtJu3cdOe71sZrLpwO02j1Y0iFn/HdanQt742rJ95LiZaoRcfB96mdwIIwg98OH3ElfQigebQez+VN19BgWYGV9yqtxSy5GRHwkKR5bQ0tvGXae2yZfDL9XxbRr1MYno348fsx22V32CSnOWi6iONhDd8lb3ivBbE8gQ7Ul/g13XhWwHCCa6W2xVqB7Z+1cnwZKV3UxeLphw9YyKRhgCS5YK0Blszti191GbCX3GqrvGcE8xPq5JrvxomyXnZXrq2FsgyFc6EEc4sGQMJF4o6N5sB+5R7txxoKwNOKjmqG8p7/PVxvUV38aczAN6ovDxvv18f+ovnoShpsgXQIDAQABAoIBAHySIv/ajF0If4hVmZxj0BsvakJpPJH75iWLLohC3UPKBZUfNex82pYH3rGKodvfRwmn0e8EDjTznSrjjQ+ISmf9+4jXdRxtYX6E/d8D0aMSOEJ5iBHumPKLTegbaqzNhyulA/n3Ok4esvWO7Tn53luJOwa9fbcudocNFUaAmsDWNP/rieXXWvV5ubtWpSmCVVQMyyVWWo3RWEC1xWzb6OCbIu/mK7TKyd1+Yym3Y9/78uOiUzjaPHr7JjxIkqt0W9FN1V8Wm5xPo7TfY+103IZIPoA46D/YtQlglxHI0aBWW/II2sthahNdC2kZTOJ4J7KugfkcbmHmoR9DWgK6uNkCgYEA3RTv1W37vf3Pfdw4wZpm0ryh7D071z5K0sxALJqhHq5hchBRx8RwGQgjp0opB9gS4j3wwJmNbwjgJkRCfGMCMYVw8vbAxTtxjjIVSRjDimXSBAx6Q28DvjSGFHXiaCoILSRU0vr6ACg6dv9HpODWy9JnfaKT5gh3zoyRyccdk+8CgYEAwpJCM1AmFNOGYyfIG5VHhcExKVLO8y0qzS+EeJG/eSW8ZrYTiwBGs38t8XyOSeZIU1K/I/pHD2QHbimk2TjCvimLZb+DcDl++WX+APi5ZjAOaaOWot2dZ20sZ6Pl6MBnAbr+WPczm5W8ag184kBeMxrWnaxIEkgSian8TLhtFHMCgYAvHAADHb2P/Z6SNjQN5SXV8AYc/etbcVWmV4mxN33vuL7g/GNAyzYLz3Uxd5cIqd1UQlij4dSGfYCuBsuYD8zu2n13+GaZYJJQ95Ebk2BPhGTdIf+HkQdeJ3kOsRP+mD5HyD8e+gX9tJTIuJr+oj6DDiGpXtRfJxzIcaG7OmeuFwKBgC2pTUflg0pX6a3TZC609bf6AqOD/3UqIGVOxXPWIG054eDo0eVJB06QhiOp62qEVGzZemnjDlIaU3QS6dDgdTNTZJdYPmxT0eyNdvKbbEcC+B7qeSt3fr0K7eTUndvla0cIrzAJs17L4Q+yYqBmIrUzkzIlgDRqHY+ZCNCoZ1DpAoGBALdRffUEHP8x9g7jW7A/vipIsUX2Qli/80KQ8TFPnPjINHa4tn2afIzxbY9l0+kjnNbjOV078cWagR6ymr3zkkNAlroTh8dy6zuBLsIXxoy872F6MHFQRHvTI4P4QI7/BlczvUcgFLW0jJsIu+Tu9upk9OJTlYV2MRkg7oNWhg3T";
        ////支付宝的公钥，由支付宝生成
        //public static string alipayPublicKey = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApUmm9/JSozrSWWXWqQyfBgMArydYxEvBgDxHprHn9PPb4DM24XbkG2L3Jfh0R0iDeVDSxvW5RWgPhkA76k4eEUL3F+AiolhUcmdNB2zlswXq0uK8YHW2YL1HD5B/JW3pie9STwSTa6y5iL6NfLJ7dLTu90FNEzaRS9Q9e7LWx66sW0eAYpoQfLrhRUijGngWTvXVlf1X/P+sYftFgYRUuKa5PNWwWRXnh3N75lYYogavDhxucAhEBG8h2vwc77fgxclXPMsmXcVxktqJb1V9CxMX7r+novEHq1lFYDCJJAknoIDK2NbBMjzUGNXodplfnkXTknXL5CklJBwJyEjtDwIDAQAB";


        ////服务器异步通知页面路径，需http://格式的完整路径，不能加?id=123这类自定义参数,必须外网可以正常访问
        ////public static string notify_url = "http://" + System.Web.HttpContext.Current.Request.Url.Host + ":" + System.Web.HttpContext.Current.Request.Url.Port + "/College/NotifyUrl";
        //public static string notify_url = "http://ryan.wicp.net/College/NotifyUrl";
        ////页面跳转同步通知页面路径，需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
        ////public static string return_url = "http://" + System.Web.HttpContext.Current.Request.Url.Host + ":" + System.Web.HttpContext.Current.Request.Url.Port + "/College/ReturnUrl";
        //public static string return_url = "http://ryan.wicp.net/College/ReturnUrl";
        ////参数返回格式，只支持json
        //public static string format = "json";
        //// 调用的接口版本，固定为：1.0
        //public static string version = "1.0";
        //// 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
        //public static string signType = "RSA2";
        //// 字符编码格式 目前支持utf-8
        //public static string charset = "utf-8";
        //// false 表示不从文件加载密钥
        //public static bool keyFromFile = false;

        ////↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
        //#region  初始化配置文件信息
        //private IAopClient GetAlipayClient()
        //{
        //    //支付宝网关地址 
        //    string serviceUrl = AlipayConfigHelper.serviceUrl;
        //    //应用ID,以2088开头由16位纯数字组成的字符串
        //    string appId = AlipayConfigHelper.appId;
        //    //商户私钥
        //    string privateKey = AlipayConfigHelper.privateKey;
        //    //支付宝的公钥
        //    string alipayPublicKey = AlipayConfigHelper.alipayPublicKey;

        //    string format = AlipayConfigHelper.format;
        //    string version = AlipayConfigHelper.version;
        //    string signType = AlipayConfigHelper.signType;
        //    string charset = AlipayConfigHelper.charset;
        //    bool keyFromFile = false;

        //    IAopClient client = new DefaultAopClient(serviceUrl, appId, privateKey, format, version, signType, alipayPublicKey, charset, keyFromFile);

        //    return client;
        //}
        //#endregion
        //#region 调用SDK生成支付表单
        //public ActionResult CreatePayForm()
        //{
        //    try
        //    {
        //        IAopClient client = GetAlipayClient();
        //        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //        //在公共参数中设置回跳和通知地址
        //        request.SetReturnUrl(AlipayConfigHelper.return_url);
        //        request.SetNotifyUrl(AlipayConfigHelper.notify_url);
        //        var RRR = Request["orderNo"].ToString();
        //        //获取订单信息
        //        DataTable dr = CollectService.GetOrderInfo(RRR).Tables[0];

        //        //方法1：
        //        AlipayTradePayModel model = new AlipayTradePayModel();
        //        //填充业务参数
        //        model.Body = "商学院报名";                    //订单描述
        //        model.Subject = "商学院报名";                 //订单标题
        //        model.OutTradeNo = Request["orderNo"];        //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
        //        model.TotalAmount = (Convert.ToInt32(dr.Rows[0]["Amount"]) * 1.0 / 100).ToString();           //订单总金额，单位为元，精确到小数点后两位
        //        model.ProductCode = "FAST_INSTANT_TRADE_PAY"; //销售产品码，商家和支付宝签约的产品码 (如 FAST_INSTANT_TRADE_PAY)
        //        request.SetBizModel(model);

        //        //方法2：
        //        /**************************************************
        //        string Body = "商学院报名";
        //        string Subject = "商学院报名";
        //        string OutTradeNo = Request["orderNo"];
        //        string TotalAmount = Request["amount"];
        //        string ProductCode = "FAST_INSTANT_TRADE_PAY";
        //        request.BizContent = "{" +
        //            "    \"body\":\""+ Body + "\"," +
        //            "    \"subject\":\""+ Subject + "\"," +
        //            "    \"out_trade_no\":\""+ OutTradeNo + "\"," +
        //            "    \"total_amount\":"+ TotalAmount + "," +
        //            "    \"product_code\":\""+ ProductCode + "\"" +
        //            "  }";
        //        *********************************************************/


        //        //调用SDK生成表单
        //        AlipayTradePagePayResponse response = client.pageExecute(request);
        //        string form = response.Body;
        //        //Response.Write(form);
        //        return Content(form);
        //    }
        //    catch (Exception e)
        //    {
        //        throw new Exception(e.Message);
        //    }
        //}
        //#endregion
        //#region 页面跳转同步通知页面
        ///// <summary>
        ///// 功能：页面跳转同步通知页面
        ///// </summary>
        //public ActionResult ReturnUrl()
        //{
        //    // http://localhost:10231/College/ReturnUrl?
        //    // total_amount =0.01
        //    // ×tamp=2017-07-24+17%3A57%3A08
        //    // &sign=********
        //    // &trade_no=2017072421001004930200313969
        //    // &sign_type=RSA2
        //    // &auth_app_id=2016080500169628
        //    // &charset=utf-8
        //    // &seller_id=2088102169996595
        //    // &method=alipay.trade.page.pay.return
        //    // &app_id=2016080500169628
        //    // &out_trade_no=GM201707241756580000000001
        //    // &version=1.0 
        //    //将同步通知中收到的所有参数都存放到map中
        //    IDictionary<string, string> map = GetRequestGet();
        //    if (map.Count > 0) //判断是否有带返回参数
        //    {
        //        try
        //        {
        //            //支付宝的公钥
        //            string alipayPublicKey = AlipayConfigHelper.alipayPublicKey;
        //            string signType = AlipayConfigHelper.signType;
        //            string charset = AlipayConfigHelper.charset;
        //            bool keyFromFile = false;
        //            // 获取支付宝GET过来反馈信息  
        //            bool verify_result = AlipaySignature.RSACheckV1(map, alipayPublicKey, charset, signType, keyFromFile);
        //            if (verify_result)
        //            {
        //                // 验证成功 
        //                Response.Redirect("/College/Index?id=1");
        //                return Content("ok");
        //            }
        //            else
        //            {
        //                return Content("验证失败");
        //            }
        //        }
        //        catch (Exception e)
        //        {
        //            throw new Exception(e.Message);
        //        }
        //    }
        //    else
        //    {
        //        return Content("无返回参数");
        //    }
        //}

        ///// <summary>
        ///// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
        ///// </summary>
        ///// <returns>request回来的信息组成的数组</returns>
        //public IDictionary<string, string> GetRequestGet()
        //{
        //    int i = 0;
        //    IDictionary<string, string> sArray = new Dictionary<string, string>();
        //    NameValueCollection coll;
        //    //Load Form variables into NameValueCollection variable.
        //    coll = Request.QueryString;

        //    // Get names of all forms into a string array.
        //    String[] requestItem = coll.AllKeys;

        //    for (i = 0; i < requestItem.Length; i++)
        //    {
        //        sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
        //    }
        //    return sArray;
        //}
        //#endregion
        //#region 服务器异步通知页面
        ///// <summary>
        ///// 功能：服务器异步通知页面
        ///// 创建该页面文件时，请留心该页面文件中无任何HTML代码及空格
        ///// 该页面不能在本机电脑测试，请到服务器上做测试。请确保外部可以访问该页面。
        ///// 该页面调试工具请使用写文本函数logResult。
        ///// 如果没有收到该页面返回的 success 信息，支付宝会在24小时内按一定的时间策略重发通知
        ///// GmkCollege
        ///// </summary>
        //public void NotifyUrl()
        //{
        //    // 获取支付宝Post过来反馈信息
        //    IDictionary<string, string> map = GetRequestPost();
        //    if (map.Count > 0) //判断是否有带返回参数
        //    {
        //        try
        //        {
        //            //支付宝的公钥
        //            string alipayPublicKey = AlipayConfigHelper.alipayPublicKey;
        //            string signType = AlipayConfigHelper.signType;
        //            string charset = AlipayConfigHelper.charset;
        //            bool keyFromFile = false;

        //            bool verify_result = AlipaySignature.RSACheckV1(map, alipayPublicKey, charset, signType, keyFromFile);
        //            // 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
        //            if (verify_result)
        //            {
        //                //商户订单号
        //                string out_trade_no = map["out_trade_no"];
        //                //支付宝交易号
        //                string trade_no = map["trade_no"];
        //                //交易创建时间
        //                string gmt_create = map["gmt_create"];
        //                //交易付款时间
        //                string gmt_payment = map["gmt_payment"];
        //                //通知时间
        //                string notify_time = map["notify_time"];
        //                //通知类型  trade_status_sync
        //                string notify_type = map["notify_type"];
        //                //通知校验ID
        //                string notify_id = map["notify_id"];
        //                //开发者的app_id
        //                string app_id = map["app_id"];
        //                //卖家支付宝用户号
        //                string seller_id = map["seller_id"];
        //                //买家支付宝用户号
        //                string buyer_id = map["buyer_id"];
        //                //实收金额
        //                string receipt_amount = map["receipt_amount"];
        //                //交易状态
        //                //交易状态TRADE_FINISHED的通知触发条件是商户签约的产品不支持退款功能的前提下，买家付款成功；
        //                //或者，商户签约的产品支持退款功能的前提下，交易已经成功并且已经超过可退款期限
        //                //状态TRADE_SUCCESS的通知触发条件是商户签约的产品支持退款功能的前提下，买家付款成功
        //                if (map["trade_status"] == "TRADE_FINISHED" || map["trade_status"] == "TRADE_SUCCESS")
        //                {
        //                    //判断该笔订单是否在商户网站中已经做过处理
        //                    DataTable dd = CollectService.OrderPayNot(out_trade_no).Tables[0];
        //                    if (Convert.ToInt32(dd.Rows[0]["Status"]) == 0)
        //                    {
        //                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
        //                        #region 将数据提添加到集合中
        //                        Dictionary<string, string> myDic = new Dictionary<string, string>();
        //                        myDic.Add("PayTradeNo", trade_no);
        //                        myDic.Add("Status", "1");
        //                        myDic.Add("Type", "0");
        //                        myDic.Add("PayTime", gmt_payment);
        //                        myDic.Add("BuyerId", buyer_id);
        //                        myDic.Add("OrderNo", out_trade_no);
        //                        #endregion 

        //                        #region 添加数据到数据库 
        //                        //bool res = collegeService.AddPayInfo(myDic);
        //                        //if (res == false)
        //                        //{
        //                        //    Response.Write("添加支付信息失败!");
        //                        //}
        //                        #endregion

        //                        Response.Write("success");  //请不要修改或删除
        //                    }
        //                }
        //            }
        //            // 验签失败则记录异常日志，并在response中返回failure.
        //            else
        //            {
        //                Response.Write("验证失败");
        //            }
        //        }
        //        catch (Exception e)
        //        {
        //            throw new Exception(e.Message);
        //        }
        //    }
        //    else
        //    {
        //        Response.Write("无返回参数");
        //    }
        //}

        ///// <summary>
        ///// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
        ///// </summary>
        ///// <returns>request回来的信息组成的数组</returns>
        //public IDictionary<string, string> GetRequestPost()
        //{
        //    int i = 0;
        //    IDictionary<string, string> sArray = new Dictionary<string, string>();
        //    NameValueCollection coll;
        //    //Load Form variables into NameValueCollection variable.
        //    coll = Request.Form;

        //    // Get names of all forms into a string array.
        //    String[] requestItem = coll.AllKeys;

        //    for (i = 0; i < requestItem.Length; i++)
        //    {
        //        sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
        //    }
        //    return sArray;
        //}
        //#endregion
        //#region 退款
        ///// <summary>
        ///// 支付宝退款
        ///// </summary>
        ///// <returns></returns>
        //public string Refund(string OrderNo)
        //{
        //    //查询要退款的订单信息
        //    DataTable dt = collegeService.GetOrderInfo(OrderNo).Tables[0];
        //    IAopClient client = GetAlipayClient();
        //    AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        //    AlipayTradePayModel model = new AlipayTradePayModel();
        //    //填充业务参数  
        //    request.BizContent = "{" +
        //    "    \"out_trade_no\":\"" + dt.Rows[0]["OrderNo"] + "\"," +
        //    "    \"trade_no\":\"" + dt.Rows[0]["TradeNo"] + "\"," +
        //    "    \"refund_amount\":" + ((int)dt.Rows[0]["Amount"] * 1.0 / 100) + "," +
        //    "    \"refund_reason\":\"正常退款\"," +
        //    "    \"operator_id\":\"OP001\"," +
        //    "    \"store_id\":\"NJ_S_001\"," +
        //    "    \"terminal_id\":\"NJ_T_001\"" +
        //    "  }";

        //    AlipayTradeRefundResponse response = client.Execute(request);
        //    string Info = response.Body;
        //    //{ "alipay_trade_refund_response":{
        //    //"code":"10000",            //"msg":"Success",
        //    //"buyer_logon_id":"xso***@sandbox.com",
        //    //"buyer_user_id":"2088102172262939",            //"fund_change":"Y",
        //    //"gmt_refund_pay":"2017-07-31 15:28:08",             //"open_id":"20881027348761637209827442915993",
        //    //"out_trade_no":"GM201707311527020000000001",
        //    //"refund_fee":"33.33",
        //    //"send_back_fee":"0.00",
        //    //"trade_no":"2017073121001004930200315623"},
        //    //"sign":"**********"}

        //    if (response.Code == "10000")
        //    {
        //        int RefundAmount = Convert.ToInt32(Convert.ToDecimal(response.RefundFee) * 100);
        //        DateTime RefundTime = Convert.ToDateTime(response.GmtRefundPay);
        //        int Status = 2;   //已退
        //        bool res = collegeService.UpdateRefundInfo(OrderNo, RefundAmount, RefundTime, Status);
        //        return JsonHelper.DataJson(0, "退款成功！");
        //    }
        //    else
        //    {
        //        return JsonHelper.DataJson(1, "退款失败！");
        //    }
        //}
        //#endregion
    }

} 
